package com.homer.android.activity.view;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import android.app.Activity;
import android.content.SharedPreferences;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;

import com.homer.android.R;
import com.homer.android.activity.scene.EspSceneActivity;
import com.homer.android.sdk.devcie.IEspDevice;
import com.homer.android.sdk.type.devcie.IEspDeviceState;

public class DeviceSceneAdapter extends BaseAdapter {
	private LayoutInflater mInflater;

	private List<IEspDevice> mDeviceList;

	private Set<IEspDevice> mEditCheckedDevices;

	private boolean mEditable = false;

	private OnEditCheckedChangeListener mEditCheckedChangeListener;

	public static Integer[] array = null;

	private Activity activity;

	//Set<String> set = null;
	String set;
	List<String> arr = null;

	public interface OnEditCheckedChangeListener {
		void onEditCheckedChanged(CheckBox checkBox, IEspDevice device,
				boolean isChecked);
	}

	public DeviceSceneAdapter(Activity activity, List<IEspDevice> list) {
		this.activity = activity;
		mInflater = activity.getLayoutInflater();

		mDeviceList = list;
		// array = new Integer[list.size()];
		// for (int i = 0; i < list.size(); i++) {
		// array[i]=0;
		// }
		mEditCheckedDevices = new HashSet<IEspDevice>();

		// 实例化SharedPreferences对象（第一步）
		SharedPreferences mySharedPreferences = this.activity
				.getSharedPreferences("scene", Activity.MODE_PRIVATE);
		// 实例化SharedPreferences.Editor对象（第二步）

		if (null != EspSceneActivity.mSelectedGroup) {
			set = mySharedPreferences.getString(
					EspSceneActivity.mSelectedGroup.getId() + "",
					"");
		}
		arr = new ArrayList<String>();
		String[] spl = set.split("[,]");
		for (int i = 0;i<spl.length;i++) {
			String str = spl[i];
			if(str!=null&&!str.equals("")){
			    arr.add(str);
			}
		}

		if (!arr.isEmpty()) {
			array = new Integer[arr.size()];
			for (int i = 0; i < arr.size(); i++) {
			        if(arr.get(i)!=null&&!arr.get(i).equals("")){
			            array[i] = Integer.parseInt(arr.get(i));
			        }else{
			            array[i] = 0;
			        }
			}
		} else {
			array = new Integer[list.size()];
			for (int i = 0; i < list.size(); i++) {
				array[i] = 0;
			}
		}

	}

	@Override
	public int getCount() {
		return mDeviceList.size();
	}

	@Override
	public Object getItem(int position) {
		return mDeviceList.get(position);
	}

	@Override
	public long getItemId(int position) {
		return mDeviceList.get(position).getId();
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		final IEspDevice device = mDeviceList.get(position);

		// /****************主开关选择算法**************************/
		// //选择PLUG类型的，并且在线，优先选用内网在线的，如果没有内网开关在线，选择外网在线的开关，如果都没有，主开关为null
		//
		// if(!device.getDeviceState().isStateOffline()&&
		// device.getDeviceType().getSerial()== EspDeviceType.PLUG.getSerial())
		// {
		// Global.setmMainSwitch(device);
		// }
		//
		// //用在线的、内网开关将主开关替换了.
		// if(
		// device.getDeviceState().isStateLocal()&&!device.getDeviceState().isStateOffline()&&
		// device.getDeviceType().getSerial()== EspDeviceType.PLUG.getSerial()){
		// Global.setmMainSwitch(device);
		// }
		//
		// if(Global.getmMainSwitch()==null){
		// if(device.getDeviceState().isStateInternet()&&!device.getDeviceState().isStateOffline()&&
		// device.getDeviceType().getSerial()== EspDeviceType.PLUG.getSerial()){
		// Global.setmMainSwitch(device);
		// }
		// }
		// /******************************************/
		//

		if (convertView == null) {
			convertView = mInflater.inflate(R.layout.device_layout_scene, null);
		}

		convertView.setTag(device);

		// Set icon
		ImageView iconIV = (ImageView) convertView
				.findViewById(R.id.device_icon_scene);
		iconIV.setBackgroundResource(R.drawable.esp_device_icon_general);

		// Set device name
		TextView nameTV = (TextView) convertView
				.findViewById(R.id.device_name_scene);
		nameTV.setText(device.getName());

		// Set state
		IEspDeviceState state = device.getDeviceState();

		TextView statusTV = (TextView) convertView
				.findViewById(R.id.device_status_text_scene);
		switch (state.getDeviceState()) {
		case UPGRADING_LOCAL:
			statusTV.setText(R.string.esp_ui_status_upgrading_local);
			break;
		case UPGRADING_INTERNET:
			statusTV.setText(R.string.esp_ui_status_upgrading_online);
			break;
		case OFFLINE:
			statusTV.setText(R.string.esp_ui_status_offline);
			break;
		case NEW:
		case ACTIVATING:
			statusTV.setText(R.string.esp_ui_status_activating);
			break;
		case LOCAL:
			statusTV.setText(R.string.esp_ui_status_local);
			break;
		case INTERNET:
			statusTV.setText(R.string.esp_ui_status_online);
			break;

		case CLEAR:
		case CONFIGURING:
		case DELETED:
		case RENAMED:
			// shouldn't goto here
			statusTV.setText(state.getDeviceState().toString());
			break;
		}
		statusTV.append(" | " + device.getDeviceType());

		ImageView localStatusIV = (ImageView) convertView
				.findViewById(R.id.device_status1_scene);
		localStatusIV.setBackgroundResource(R.drawable.esp_device_status_local);
		localStatusIV.setVisibility(state.isStateLocal() ? View.VISIBLE
				: View.GONE);

		ImageView cloudStatusIV = (ImageView) convertView
				.findViewById(R.id.device_status2_scene);
		cloudStatusIV.setVisibility(device.isActivated() ? View.VISIBLE
				: View.GONE);
		if (state.isStateInternet()) {
			cloudStatusIV
					.setBackgroundResource(R.drawable.esp_device_status_cloud);
		} else {
			cloudStatusIV
					.setBackgroundResource(R.drawable.esp_device_status_offline);
		}

		final CheckBox editCB = (CheckBox) convertView
				.findViewById(R.id.edit_check_scene);
		boolean isChecked = mEditCheckedDevices.contains(device) ? true : false;
		editCB.setChecked(isChecked);
		editCB.setChecked(isChecked);
		editCB.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				boolean isChecked = editCB.isChecked();
				if (isChecked) {
					mEditCheckedDevices.add(device);
				} else {
					mEditCheckedDevices.remove(device);
				}

				if (mEditCheckedChangeListener != null) {
					mEditCheckedChangeListener.onEditCheckedChanged(editCB,
							device, isChecked);
				}
			}
		});

		View statusContent = convertView
				.findViewById(R.id.status_content_scene);
		if (mEditable) {
			statusContent.setVisibility(View.GONE);
			editCB.setVisibility(View.VISIBLE);
		} else {
			statusContent.setVisibility(View.VISIBLE);
			editCB.setVisibility(View.GONE);
		}

		RadioGroup switch_status = null;

		switch_status = (RadioGroup) convertView
				.findViewById(R.id.switch_status);
		final RadioButton on = (RadioButton) convertView.findViewById(R.id.on);
		final RadioButton off = (RadioButton) convertView
				.findViewById(R.id.off);
		try {
			if (arr.size() == array.length) {
				String value = arr.get(position);
				if (value.equals("1")) {
					on.setChecked(true);
					off.setChecked(false);

				}
				if (value.equals("0")) {
					on.setChecked(false);
					off.setChecked(true);
				}

			}
		} catch (Exception e) {

		}

		switch_status.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				try {
					if (on.getId() == checkedId) {
						array[position] = 1;
					} else if (off.getId() == checkedId) {
						array[position] = 0;
					}

				} catch (Exception e) {
					e.printStackTrace();
				}

			}
		});

		return convertView;
	}

	public void setEditable(boolean editable) {
		mEditable = editable;
	}

	public boolean isEditable() {
		return mEditable;
	}

	public Set<IEspDevice> getmEditCheckedDevices() {
		return mEditCheckedDevices;
	}

	public void setmEditCheckedDevices(Set<IEspDevice> mEditCheckedDevices) {
		this.mEditCheckedDevices = mEditCheckedDevices;
	}

	public void setOnEditCheckedChangeListener(
			OnEditCheckedChangeListener listener) {
		mEditCheckedChangeListener = listener;
	}
}

